var mongoose = require("mongoose");
var Connection = require("./connection");
var DeviceACL = require("./device_acl");
var emqxService = require("../services/emqx_service");
var Schema = mongoose.Schema;
const deviceSchema = new Schema({
    //ProductName
    product_name: {
        type: String,
        required: true,
    },
    //DeviceName
    device_name: {
        type: String,
        required: true,
    },
    //接入 EMQ X 时使用的 username
    broker_username: {
        type: String,
        required: true,
    },
    //secret
    secret: {
        type: String,
        required: true,
    },
    //可接入状态
    status: String,
});

//定义 device.toJSONObject
deviceSchema.methods.toJSONObject = function () {
    return {
        product_name: this.product_name,
        device_name: this.device_name,
        secret: this.secret,
    };
};

deviceSchema.statics.addConnection = function (event) {
    if (event.username != null) {
        var username_arr = event.username.split("/");
        let productName = username_arr[0];
        let deviceName = username_arr[1];
        this.findOne(
            { product_name: productName, device_name: deviceName },
            function (err, device) {
                if (err == null && device != null) {
                    Connection.findOneAndUpdate(
                        {
                            clientid: event.clientid,
                            device: device._id,
                        },
                        {
                            connected: true,
                            clientid: event.clientid,
                            keepalive: event.keepalive,
                            ipaddress: event.ipaddress,
                            proto_ver: event.proto_ver,
                            connected_at: event.connected_at,
                            device: device._id,
                        },
                        { upsert: true, useFindAndModify: false, new: true }
                    ).exec();
                }
            }
        );
    }
};

deviceSchema.statics.removeConnection = function (event) {
    if (event.username != null) {
        var username_arr = event.username.split("/");
        let productName = username_arr[0];
        let deviceName = username_arr[1];
        this.findOne(
            { product_name: productName, device_name: deviceName },
            function (err, device) {
                if (err == null && device != null) {
                    Connection.findOneAndUpdate(
                        { clientid: event.clientid, device: device._id },
                        {
                            connected: false,
                            disconnect_at: Math.floor(Date.now() / 1000),
                        },
                        { useFindAndModify: false }
                    ).exec();
                }
            }
        );
    }
};
//禁用
deviceSchema.methods.disconnect = function () {
    Connection.find({ device: this._id }).exec(function (err, connections) {
        connections.forEach(function (conn) {
            emqxService.disconnectClient(conn.clientid);
        });
    });
};

/**
 * 返回某个设备可以订阅和发布的主题
 */
deviceSchema.methods.getACLRule = function () {
    const publish = [`upload_data/${this.productName}/${this.deviceName}/+/+`];
    const subscribe = [];
    const pubsub = [];
    return {
        publish: publish,
        subscribe: subscribe,
        pubsub: pubsub,
    };
};

/**
 * 在删除设备时，删除所有的连接信息
 */
deviceSchema.post("remove", function (device, next) {
    Connection.deleteMany({ device: device._id }).exec();
    DeviceACL.deleteMany({ broker_username: device.broker_username }).exec();
    next();
});

const Device = mongoose.model("Device", deviceSchema);

module.exports = Device;
